/**
 * Created by Jimmy on 7/2/2015.
 */

package fyp.spedmew.util;

import android.util.Log;

import com.google.api.client.util.DateTime;

import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Utility {

    private static final String TAG = new Object(){}.getClass().getCanonicalName();

    // Return a hashed string
    public static String getHash(String base) {
        String message = "";

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(base.getBytes("UTF-8"));
            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            message = hexString.toString();

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        return message;
    }

    public static String charArrayToString(char[] charArray) {
        String text = "";
        for (int i = 0; i < charArray.length; i++) {
            text = text + charArray[i];
        }

        return text;
    }

    // This method verified the user name
    public static boolean checkLoginname(String userName) {
        if (userName.isEmpty())                        // check if username is empty
            return false;
        else if (userName.contains(" "))                // check for whitespace
            return false;

        return true;
    }

    // This method verified the password
    public static boolean checkPassword(String password) {
        final int passwordLength = 6;
        char ch;

        if (password.length() < passwordLength)        // check length of password
            return false;
        else if (password.contains(" "))                // check for whitespace
            return false;
        else if (!password.matches(".*\\d.*"))        // check if numeric character is present
            return false;
        else if (password.matches("^\\d*$"))            // check if non-numeric character is present
            return false;

        return true;
    }

    /**
     * Convert a string in dd/mm/yyyy to DateTime object
     */
    public static DateTime convertStringToDateTime(String dateStr) {
        try {
            Date date = new SimpleDateFormat("dd/MM/yyyy").parse(dateStr);
            return new DateTime(date);
        } catch (ParseException e) {
            Log.e(Utility.TAG, "Can not convert " + dateStr + " to date");
        }
        return null;
    }
}
